package com.base.stack;

import java.util.Iterator;
import java.util.Objects;
import java.util.Stack;

/**
 * TODO
 *
 * @author leon
 * @date 2022年01月06日 10:48
 */
public class SimplifyPath {
    public String simplifyPath(String path) {
        String[] paths = path.split("/");

        Stack<String> stack = new Stack<>();
        for(int i=0;i<paths.length;i++){
            if(Objects.equals(paths[i], "..")){
                // 上层目录
                if(stack.isEmpty()){
                    continue;
                }
                stack.pop();
            }else if(!Objects.equals(paths[i], ".") && !Objects.equals(paths[i], "")){
                stack.push("/"+paths[i]);
            }
        }
        if(stack.isEmpty()){
            return "/";
        }
        Iterator<String> iterator = stack.iterator();
        StringBuilder sb = new StringBuilder();
        while (iterator.hasNext()){
            sb.append(iterator.next());
        }

        return sb.toString();

    }

    public static void main(String[] args) {
        System.out.println(new SimplifyPath().simplifyPath("/home/leon/..//../"));
    }
}
